/* Simple Class to Plot RB stats 
   Author: O. van der Aa 
   Email: o.van-der-aa@imperial.ac.uk */
using namespace std;
#include "RBPlot.h"

#include "TTree.h"
#include "TDatime.h"
#include <TStyle.h> 
#include <TPad.h>
#include <THStack.h>
#include <TLegend.h>
#include <TPaveText.h>
#include <TPaveLabel.h>
#include <TCanvas.h>
#include <TEventList.h>
#include <TObjString.h>

#include "TFile.h"
#include "TH1.h"
#include "TH2D.h"

#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <fstream>

RBPlot::RBPlot(TTree* tree) { mytree=tree; gROOT->SetStyle("Plain"); gStyle->SetOptStat(10); } 

RBPlot::RBPlot(char* filename) { 
	myfile=new TFile(filename); 
	myfile->cd(0); 
	mytree=(TTree*)myfile->FindObjectAny("tree"); 
	gROOT->SetStyle("Plain"); gStyle->SetOptStat(10);	
}

void RBPlot::doNJobsCEVO(char* sdate,char* edate,TCut cuts,char* hname) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	mytree->Draw(Form("VO.fData:CE.fData >> %s",hname),cuts,"goff");	
//	TH2F* myhisto=(TH2F*)gROOT->FindObject(hname);
}


void RBPlot::doJobEffi(char* sdate,char* edate,Int_t nbins,TCut cuts,char* hname) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TH1F* t1h=new TH1F(Form("njobs_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* t2h=new TH1F(Form("nSjobs_%s",hname),hname,nbins,interval.first,interval.second);
	t1h->Reset();
	t2h->Reset();
	mytree->Draw(Form("userinterface_regjob_Epoch >> njobs_%s",hname),cuts,"goff");
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
	mytree->Draw(Form("userinterface_regjob_Epoch >> nSjobs_%s",hname),cuts && suc,"goff");
	// will now devide to have the efficiency
	TH1F* je=(TH1F*)t2h->Clone(Form("JobEffi_%s",hname)); 
	je->Divide(t1h);
}

void RBPlot::doJobRunTime(char* sdate,char* edate,Int_t nbins,TCut cuts,char* hname) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TH1F* r1h=new TH1F(Form("r1h_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* r2h=new TH1F(Form("r2h_%s",hname),hname,nbins,interval.first,interval.second);
	r1h->Reset();
	r2h->Reset();
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
	TString myruntime="(logmonitor_wn_Time/3600)";
	mytree->Draw(Form("userinterface_regjob_Epoch >> r1h_%s",hname),myruntime*cuts,"goff");
	mytree->Draw(Form("userinterface_regjob_Epoch >> r2h_%s",hname),myruntime*(cuts && suc),"goff");
	TH1F* rd=(TH1F*)r2h->Clone(Form("UFTEffi_%s",hname));
	rd->Divide(r1h);
	// will now devide to have the efficiency
}


void RBPlot::graph(char* var,char* sdate,char* edate,Int_t dt,TCut cuts,char* hname,char* yname,char* xname, char* title) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	char* histoname=Form("%s_%s",var,hname);
	TH1F* histo=new TH1F(histoname,hname,nbins,interval.first,interval.second);
 	mytree->Draw(Form("%s >> %s",var,histoname),cuts,"goff");	
	histo->GetXaxis()->SetTimeDisplay(1);
	histo->SetXTitle(xname);
	histo->SetYTitle(yname);
	histo->Draw(title);
	gPad->SetGridy();
}


void RBPlot::totalJobs(char* sdate,char* edate,Int_t dt,TCut cuts,char* hname) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	TH1F* failed=new TH1F(Form("failed_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* success=new TH1F(Form("success_%s",hname),hname,nbins,interval.first,interval.second); 
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
 //	TCut rrs("type.fData==\"REGISTERED-RAN-SUCCESS\"");
//	TCut rrrs("type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
	mytree->Draw(Form("userinterface_regjob_Epoch >> failed_%s",hname),cuts&&(!(suc)),"goff");	
	mytree->Draw(Form("userinterface_regjob_Epoch >> success_%s",hname),cuts&&(suc),"goff");	
	TH1F* total=(TH1F*)success->Clone(Form("totaljobs_%s",hname));
	TH1F* jobeffi=(TH1F*)success->Clone(Form("effi_%s",hname));
	failed->SetFillColor(2);
	success->SetFillColor(3);
	success->GetXaxis()->SetTimeDisplay(1);
	success->SetXTitle("Time");
	success->SetYTitle("Njobs");
	THStack* stack=new THStack("Njobs_stack",hname);
	stack->Add(failed);
	stack->Add(success);
	TLegend* leg=new TLegend(0.8,0.8,0.89,0.89);
	leg->AddEntry(failed,Form("Failed Jobs=%.0f",failed->GetEntries()),"f");
	leg->AddEntry(success,Form("Success Jobs=%.0f",success->GetEntries()),"f");
//	Double_t totaljobs=failed->GetEntries()+success->GetEntries();
//	TPaveLabel* text=new TPaveLabel(0.1,0.1,0.89,0.89,Form("Number of jobs=%f",totaljobs));
	TCanvas* cv=new TCanvas("Jobs","Jobs");
	cv->Divide(1,2);
	cv->cd(1);
	stack->Draw();
	stack->GetXaxis()->SetTimeDisplay(1);
	stack->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");
	stack->GetXaxis()->SetTitle("Time");
	stack->GetYaxis()->SetTitle("Total Jobs");
	stack->GetXaxis()->SetTitleSize(0.05);
	stack->GetXaxis()->SetLabelSize(0.05);
	stack->GetYaxis()->SetTitleOffset(0.8);
	stack->GetYaxis()->SetTitleSize(0.05);
	stack->GetYaxis()->SetLabelSize(0.05);
	leg->Draw();
	gPad->SetGridy();
	cv->cd(2);
	total->Add(failed);
	jobeffi->Divide(total);
	jobeffi->SetTitle("");
	jobeffi->Draw();
	jobeffi->GetXaxis()->SetTitleSize(0.05);
	jobeffi->GetXaxis()->SetLabelSize(0.05);
	jobeffi->GetYaxis()->SetTitleOffset(0.5);
	jobeffi->GetYaxis()->SetTitleSize(0.05);
	jobeffi->GetYaxis()->SetLabelSize(0.05);
	jobeffi->SetXTitle("Time");
	jobeffi->SetYTitle("efficiency");
	jobeffi->GetXaxis()->SetTimeDisplay(1);
	jobeffi->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");	
	jobeffi->SetFillColor(5);
//	jobeffi->LabelsOption(">","X");
/*
	TH1F* total=new TH1F(Form("totaljobs_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* effi=new TH1F(Form("effi_%s",hname),hname,nbins,interval.first,interval.second); 
	mytree->Draw(Form("userinterface_regjob_Epoch >> totaljobs_%s",hname),cuts,"goff");	
	mytree->Draw(Form("userinterface_regjob_Epoch >> effi_%s",hname),cuts&&(rrs||rrrs),"goff");	
	effi->Divide(total);	
	gStyle->SetOptStat(0);
	effi->Draw();
	effi->SetXTitle("Time");
	effi->SetYTitle("efficiency");
	effi->GetXaxis()->SetTimeDisplay(1);
	effi->SetFillColor(4);
	*/
//	text->Draw();
	gPad->SetGridy();
}

void RBPlot::printIntervalEpoch(char* sdate,char* edate) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	cout << "[" << interval.first << "," << interval.second << "]" << endl;
}

void RBPlot::jobRBCEMatrix(char* sdate, char* edate,TCut cuts,char* hname) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TCut datecut(Form("userinterface_regjob_Epoch > %d && userinterface_regjob_Epoch < %d",interval.first,interval.second));
	mytree->Draw(Form("CE.fData:RB.fData >> cerb_%s",hname),datecut&&cuts,"goff");	
	TH2F* cerbh=(TH2F*)gROOT->FindObject(Form("cerb_%s",hname));		
	THashList* xnames=cerbh->GetXaxis()->GetLabels();	
	THashList* ynames=cerbh->GetYaxis()->GetLabels();	
	ofstream file(hname);
	file << "Date inteval is [" << sdate << "|" << edate << "]" << endl; 
	file << "Constrains are [" << (const char*)cuts << "]" << endl;
	file << "Name\t";
	for(int j=0; j<=xnames->LastIndex();j++) {
		file << ((TObjString*)xnames->At(j))->GetString() << "\t";	
	}
	file << endl;
	for(int i=0; i<=ynames->LastIndex(); i++) {
		file << ((TObjString*)ynames->At(i))->GetString() << "\t";
		for(int j=0; j<=xnames->LastIndex(); j++) {
			file << cerbh->GetBinContent(cerbh->GetBin(j+1,i+1)) << "\t";	
		}
		file << endl;
	}
}


void RBPlot::activeJobs(char* sdate,char* edate,Int_t dt,TCut andcut,char* list) {
    vector<TCut*>  cuts;
    gStyle->SetOptStat(0);
// create the cut list
    TString st(list);
    TObjArray* tok=st.Tokenize(" ");
//    if(cuts.size()!=0) for(unsigned int i=0; i<cuts.size(); i++) delete cuts[i];
    cout << "clear" << endl;
    cuts.clear();
    cout << "end clear" << endl;
    for(int i=0; i<tok->GetEntriesFast();i++) {
	TString atoken=((TObjString*)tok->At(i))->GetString();
	TObjArray* subtokens=atoken.Tokenize("$");
	if(subtokens->GetEntriesFast()==2) { 
		TString p1=((TObjString*)subtokens->At(0))->GetString(); 
		TString p2=((TObjString*)subtokens->At(1))->GetString(); 
		TCut cut(p1,p2);	
		cuts.push_back(new TCut(p1,p2));
//	cout << p1 << " " << p2 << endl;
	}
    }
// -----------------
	mytree->GetDirectory()->cd("..");
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	vector<TCut*>::iterator icuts;
       for(icuts=cuts.begin();icuts!=cuts.end(); icuts++) {
		(*icuts)->Print();
		TH1D* c;
		c=new TH1D(Form("reg_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
		c=new TH1D(Form("end_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
		c=new TH1D(Form("Ireg_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
		c=new TH1D(Form("Iend_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
	}
/*
	 for(icuts=cuts.begin();icuts!=cuts.end(); icuts++) {
		(*icuts)->Print();
		TH1D* c=(TH1D*)gROOT->FindObject(Form("reg_%s",(*icuts)->GetName()));
		if(c!=NULL) c->Reset();
		else c=new TH1D(Form("reg_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
	}
        for(icuts=cuts.begin();icuts!=cuts.end(); icuts++) {
		TH1D* c=(TH1D*)gROOT->FindObject(Form("end_%s",(*icuts)->GetName()));
		if(c!=NULL) c->Reset();
		else c=new TH1D(Form("end_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
	}
        for(icuts=cuts.begin();icuts!=cuts.end(); icuts++) {
		TH1D* c=(TH1D*)gROOT->FindObject(Form("Ireg_%s",(*icuts)->GetName()));
		if(c!=NULL) c->Reset();
		else c=new TH1D(Form("Ireg_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
	}
        for(icuts=cuts.begin();icuts!=cuts.end(); icuts++) {
		TH1D* c=(TH1D*)gROOT->FindObject(Form("Iend_%s",(*icuts)->GetName()));
		if(c!=NULL) c->Reset();
		else c=new TH1D(Form("Iend_%s",(*icuts)->GetName()),"active jobs",nbins,interval.first,interval.second);	
	}
	*/
// ----------------
	cout << "end of hists" << endl;
	Int_t col=1;
	THStack* stack=new THStack("active","active");
	TLegend* leg=new TLegend(0.8,0.8,0.89,0.89);
	for(icuts=cuts.begin();icuts!=cuts.end();icuts++) {
		cerr << "-";
		mytree->Draw(Form("logmonitor_running_Epoch >> reg_%s",(*icuts)->GetName()),**icuts&&"logmonitor_done_Epoch!=0 && logmonitor_running_Epoch!=0"&&andcut,"goff");
		cerr << "+";
		mytree->Draw(Form("logmonitor_done_Epoch >> end_%s",(*icuts)->GetName()),**icuts&&"logmonitor_done_Epoch!=0 && logmonitor_running_Epoch!=0"&&andcut,"goff");
		TH1D* regh=(TH1D*)gROOT->FindObject(Form("reg_%s",(*icuts)->GetName()));		
		TH1D* Iregh=(TH1D*)gROOT->FindObject(Form("Ireg_%s",(*icuts)->GetName()));
		TH1D* endh=(TH1D*)gROOT->FindObject(Form("end_%s",(*icuts)->GetName()));		
		TH1D* Iendh=(TH1D*)gROOT->FindObject(Form("Iend_%s",(*icuts)->GetName()));
		for(int i=1;i<=regh->GetNbinsX();i++) {
			Iregh->SetBinContent(i,regh->Integral(1,i));	
			Iendh->SetBinContent(i,endh->Integral(1,i));
		}
		Iregh->Add(Iendh,-1);
		Iregh->SetFillColor(col++);
		leg->AddEntry(Iregh,Form("%s",(*icuts)->GetName()),"f");
		stack->Add(Iregh);
	}
	cerr << endl;
	stack->Draw();
	stack->GetXaxis()->SetTimeDisplay(1);
	stack->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");
	leg->Draw();
	// integration
	
/*
	TH1D* runjob=new TH1D("run",hname,nbins,interval.first,interval.second);
        TH1D* stopjob=new TH1D("stop",hname,nbins,interval.first,interval.second);
        TCut rrs("type.fData==\"REGISTERED-RAN-SUCCESS\"");
        TCut rrrs("type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
	TCut suc=(rrs||rrrs);
	TCut datecut(Form("userinterface_regjob_Epoch > %d && userinterface_regjob_Epoch < %d",interval.first,interval.second));
	mytree->Draw(">>sl",cuts&&suc&&datecut);
	TEventList *sl = (TEventList*)gDirectory->Get("sl");  
	mytree->SetEventList(sl);
	mytree->Draw("logmonitor_running_Epoch >> run");
	mytree->Draw("logmonitor_done_Epoch >> stop");
	cout << "cloning" << endl;
	TH1D* Irunjob=(TH1D*)runjob->Clone("Irun"); Irunjob->Reset();
	TH1D* Istopjob=(TH1D*)runjob->Clone("Istop"); Istopjob->Reset();
		for(int i=1;i<=runjob->GetNbinsX();i++) {
			Irunjob->SetBinContent(i,runjob->Integral(1,i));	
			Istopjob->SetBinContent(i,stopjob->Integral(1,i));
		} 
	mytree->SetEventList(NULL);
*/
}


void RBPlot::integratedJobs(char* sdate,char* edate,Int_t dt,TCut cuts,char* hname) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	TH1F* nsuccjobs=new TH1F(Form("RegSuccJobs_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* nfailjobs=new TH1F(Form("RegFailJobs_%s",hname),hname,nbins,interval.first,interval.second);
        TCut rrs("type.fData==\"REGISTERED-RAN-SUCCESS\"");
        TCut rrrs("type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
	mytree->Draw(Form("userinterface_regjob_Epoch >> RegSuccJobs_%s",hname),cuts&&(rrs||rrrs),"goff");	
	mytree->Draw(Form("userinterface_regjob_Epoch >> RegFailJobs_%s",hname),cuts&&(!(rrs||rrrs)),"goff");	
	TH1F* intnsuccjobs=(TH1F*)nsuccjobs->Clone(Form("IntRegSuccJobs_%s",hname));  
	TH1F* intnfailjobs=(TH1F*)nfailjobs->Clone(Form("IntRegFailJobs_%s",hname));  
	intnsuccjobs->Reset();
	intnfailjobs->Reset();
	for(int i=1; i<=intnsuccjobs->GetNbinsX(); i++) {
		intnsuccjobs->SetBinContent(i,nsuccjobs->Integral(1,i));
		intnfailjobs->SetBinContent(i,nfailjobs->Integral(1,i));
	}
	intnsuccjobs->SetFillColor(3);
	intnfailjobs->SetFillColor(2);
	THStack* st=new THStack(Form("IntStack_%s",hname),Form("integrated number of jobs for %s",hname));
	st->Add(intnfailjobs);
	st->Add(intnsuccjobs);
	st->Draw();
	st->GetXaxis()->SetTimeDisplay(1);
}


void RBPlot::totalHours(char* sdate,char* edate,Int_t dt,TCut cuts,char* hname) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	TH1F* failed=new TH1F(Form("Hfailed_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* success=new TH1F(Form("Hsuccess_%s",hname),hname,nbins,interval.first,interval.second); 
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
// 	TCut rrs("type.fData==\"REGISTERED-RAN-SUCCESS\"");
//	TCut rrrs("type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
//	TCut rrrs("type.fData==\"REGISTERED-RAN-SUCCESS\"");
	TString myruntime="(logmonitor_wn_Time/3600)";
	mytree->Draw(Form("userinterface_regjob_Epoch >> Hfailed_%s",hname),myruntime*(cuts&&(!(suc))),"goff");	
	mytree->Draw(Form("userinterface_regjob_Epoch >> Hsuccess_%s",hname),myruntime*(cuts&&(suc)),"goff");	
	TH1F* total=(TH1F*)success->Clone(Form("Htotaljobs_%s",hname));
	TH1F* jobeffi=(TH1F*)success->Clone(Form("Heffi_%s",hname));
	failed->SetFillColor(2);
	success->SetFillColor(3);
	success->GetXaxis()->SetTimeDisplay(1);
	success->SetXTitle("Time");
	success->SetYTitle("Job Hours");
	THStack* stack=new THStack("Njobs_stack",hname);
	failed->GetXaxis()->SetRangeUser(0,300000);
	success->GetXaxis()->SetRangeUser(0,300000);
	stack->Add(failed);
	stack->Add(success);
	TLegend* leg=new TLegend(0.8,0.8,0.89,0.89);
	leg->AddEntry(failed,Form("Failed Jobs=%f",failed->GetEntries()),"f");
	leg->AddEntry(success,Form("Success Jobs=%f",success->GetEntries()),"f");
//	Double_t totaljobs=failed->GetEntries()+success->GetEntries();
//	TPaveLabel* text=new TPaveLabel(0.1,0.1,0.89,0.89,Form("Number of jobs=%f",totaljobs));
	cout << "Total Hours Success=" << success->Integral() << " Total Hours Failed=" << failed->Integral() << " Efficiency=" << success->Integral()/(success->Integral()+failed->Integral()) << endl; 
	TCanvas* cv=new TCanvas("Jobs","Jobs");
	cv->Divide(1,2);
	cv->cd(1);
	stack->Draw();
	stack->GetXaxis()->SetTimeDisplay(1);
	stack->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");
	stack->GetXaxis()->SetTitle("Time");
	stack->GetYaxis()->SetTitle("Job Hours");
	stack->GetXaxis()->SetTitleSize(0.05);
	stack->GetXaxis()->SetLabelSize(0.05);
	stack->GetYaxis()->SetTitleOffset(0.8);
	stack->GetYaxis()->SetTitleSize(0.05);
	stack->GetYaxis()->SetLabelSize(0.05);
leg->Draw();
	gPad->SetGridy();
	cv->cd(2);
	total->Add(failed);
	//total->ResetBit(TH1::kCanRebin);
	//jobeffi->ResetBit(TH1::kCanRebin);
	jobeffi->Divide(total);
	/*
	TH1F* total=new TH1F(Form("Htotaljobs_%s",hname),hname,nbins,interval.first,interval.second);
	TH1F* effi=new TH1F(Form("Heffi_%s",hname),hname,nbins,interval.first,interval.second); 
	mytree->Draw(Form("userinterface_regjob_Epoch >> Htotaljobs_%s",hname),myruntime*cuts,"goff");	
	mytree->Draw(Form("userinterface_regjob_Epoch >> Heffi_%s",hname),myruntime*(cuts&&(rrs||rrrs)),"goff");	
	effi->Divide(total);	
	gStyle->SetOptStat(0);
	effi->Draw();
	effi->SetXTitle("Time");
	effi->SetYTitle("Usefull Time");
	effi->GetXaxis()->SetTimeDisplay(1);
	effi->SetFillColor(4);
//	text->Draw();
	*/
	jobeffi->Draw();
	jobeffi->SetXTitle("Time");
	jobeffi->SetYTitle("Efficiency (Succ Hours/Total Hours)");
	jobeffi->GetXaxis()->SetTimeDisplay(1);
	jobeffi->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");
	jobeffi->SetFillColor(5);
	jobeffi->GetXaxis()->SetTitleSize(0.05);
	jobeffi->GetXaxis()->SetLabelSize(0.05);
	jobeffi->GetYaxis()->SetTitleOffset(0.5);
	jobeffi->GetYaxis()->SetTitleSize(0.05);
	jobeffi->GetYaxis()->SetLabelSize(0.05);
	jobeffi->SetTitle("");
	gPad->SetGridy();
}

void RBPlot::activeDN(char* sdate,char* edate,Int_t dt,TCut cut,char* hname) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	Int_t nbins=getNBins(interval,dt);
	TH2D* totalDN=new TH2D(Form("ActiveDNS_%s",hname),hname,1000,0,1000,nbins,interval.first,interval.second);
	mytree->Draw(Form("userinterface_regjob_Epoch:DN.fData >> ActiveDNS_%s",hname),cut,"goff");
	TH2D* scaled=(TH2D*)totalDN->Clone(Form("ActiveDNS_Scaled_%s",hname));
	scaled->Divide(totalDN);
	TH1D* activeDN=scaled->ProjectionY();
	activeDN->Draw();
	activeDN->SetXTitle("Time");
	activeDN->SetYTitle("Number of Active DN");
	activeDN->GetXaxis()->SetTimeDisplay(1);
	activeDN->GetXaxis()->SetTimeFormat("%d/%m/%y/%F1970-01-01 00:00:00");
//	activeDN->SetFillColor(5);
	gPad->SetGridy();
}


void RBPlot::totalTimeVO(char* sdate,char* edate,TCut cut) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TH1F* histo[5];
	TCut scut(Form("userinterface_regjob_Epoch > %d",interval.first));
        TCut ecut(Form("userinterface_regjob_Epoch < %d",interval.second));
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
	mytree->Draw(">>elist",cut);
	TEventList* subset=(TEventList*)gDirectory->Get("elist");
	mytree->SetEventList(subset);
	mytree->Draw("VO.fData >> sucT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut),"goff");
	mytree->Draw("VO.fData >> failT","(logmonitor_wn_Time/3600)"*(!suc&&scut&&ecut),"goff");
	histo[0]=(TH1F*)gROOT->FindObject("sucT");
	histo[1]=(TH1F*)gROOT->FindObject("failT");
	for(int i=0; i<2;i++) { histo[i]->LabelsOption("a","X"); }
	THashList* names[5];
	for(int i=0; i<2;i++) { names[i]=histo[i]->GetXaxis()->GetLabels(); }
	map<string,double> hours[2];
	map<string,double> total;
	int maxbins=0;
	const char* current;
	for(int i=0;i<2;i++) {
		for(int j=1; j<=histo[i]->GetNbinsX();j++) {
			current=((TObjString*)(names[i]->At(j-1)))->GetString().Data();
			if(j>maxbins) maxbins=j;
			hours[i][current]=histo[i]->GetBinContent(j);
			if(i!=1) total[current]=total[current]+hours[i][current];
			cout << current << hours[i][current] << endl;
		}		
	}	
	cout << "Making total" << endl;
	TH1F* totalH=new TH1F("totalH","totalH",maxbins,0,maxbins);	
	map<string,double>::iterator itotal;
	int index=0;
	for(itotal=total.begin();itotal!=total.end();itotal++) {
		index++;
		totalH->SetBinContent(index,(*itotal).second);
		totalH->GetXaxis()->SetBinLabel(index,(*itotal).first.c_str());
	}	
	totalH->LabelsOption(">","X");
	THashList* slist=totalH->GetXaxis()->GetLabels();
	TH1F* final[5];
	vector<string> binnames;
	for(int i=0; i<2;i++) { 
		final[i]=new TH1F(Form("final_%d",i),Form("final_%d",i),maxbins,0,maxbins); 
		for(int j=1;j<=maxbins;j++) {
			 current=((TObjString*)(slist->At(j-1)))->GetString().Data();		 
			 final[i]->SetBinContent(j,hours[i][current]);
			 final[i]->GetXaxis()->SetBinLabel(j,current);
			 binnames.push_back(current);
		}
	}
	THStack* st=new THStack("CEHours","");
	for(int i=0;i<2;i++) { 
		if(i!=1) final[i]->SetFillColor(i+2); 
		st->Add(final[i]);
	}
	cout << maxbins << endl;
	st->Draw();
	for(int j=1;j<=maxbins;j++) {
		cout << binnames[j-1].c_str() << endl;
		st->GetXaxis()->SetBinLabel(j,binnames[j-1].c_str());
		st->GetXaxis()->LabelsOption("v");
	}
	TLegend* leg=new TLegend(0.8,0.8,0.89,0.89);
	leg->AddEntry(final[0],"Success","f");
	leg->AddEntry(final[1],"Failed","f");
	st->Draw();
	leg->Draw();
}


void RBPlot::totalTimeCE(char* sdate,char* edate,TCut cut) {
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TH1F* histo[5];
	TCut scut(Form("userinterface_regjob_Epoch > %d",interval.first));
        TCut ecut(Form("userinterface_regjob_Epoch < %d",interval.second));
// 	In the old root files
//	TCut suc("type.fData==\"REGISTERED-RAN-SUCCESS\" || type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
	TCut cms("VO.fData==\"cms\"");
	TCut lhcb("VO.fData==\"lhcb\"");
	TCut atlas("VO.fData==\"atlas\"");
	TCut alice("VO.fData==\"alice\"");
	TCut lhc=(cms||lhcb||atlas||alice);
	mytree->Draw(">>elist",cut);
	TEventList* subset=(TEventList*)gDirectory->Get("elist");
	mytree->SetEventList(subset);
	mytree->Draw("CE.fData >> cmsT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut&&cms),"goff");
	mytree->Draw("CE.fData >> lhcbT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut&&lhcb),"goff");
//	mytree->Draw("CE.fData >> aliceT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut&&alice),"goff");
	mytree->Draw("CE.fData >> atlasT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut&&atlas),"goff");
	mytree->Draw("CE.fData >> othersT","(logmonitor_wn_Time/3600)"*(suc&&scut&&ecut&&!lhc),"goff");
	mytree->Draw("CE.fData >> failT","(logmonitor_wn_Time/3600)"*(!suc&&scut&&ecut),"goff");
	histo[0]=(TH1F*)gROOT->FindObject("cmsT");
	histo[1]=(TH1F*)gROOT->FindObject("lhcbT");
//	histo[2]=(TH1F*)gROOT->FindObject("aliceT");
	histo[2]=(TH1F*)gROOT->FindObject("atlasT");
	histo[3]=(TH1F*)gROOT->FindObject("othersT");
	histo[4]=(TH1F*)gROOT->FindObject("failT");
	for(int i=0; i<5;i++) { histo[i]->LabelsOption("a","X"); }
	THashList* names[5];
	for(int i=0; i<5;i++) { names[i]=histo[i]->GetXaxis()->GetLabels(); }
	map<string,double> hours[5];
	map<string,double> total;
	int maxbins=0;
	const char* current;
	for(int i=0;i<5;i++) {
		for(int j=1; j<=histo[i]->GetNbinsX();j++) {
			current=((TObjString*)(names[i]->At(j-1)))->GetString().Data();
			if(j>maxbins) maxbins=j;
			hours[i][current]=histo[i]->GetBinContent(j);
			if(i!=4) total[current]=total[current]+hours[i][current];
			cout << current << hours[i][current] << endl;
		}		
	}	
	cout << "Making total" << endl;
	TH1F* totalH=new TH1F("totalH","totalH",maxbins,0,maxbins);	
	map<string,double>::iterator itotal;
	int index=0;
	for(itotal=total.begin();itotal!=total.end();itotal++) {
		index++;
		totalH->SetBinContent(index,(*itotal).second);
		totalH->GetXaxis()->SetBinLabel(index,(*itotal).first.c_str());
	}	
	totalH->LabelsOption(">","X");
	THashList* slist=totalH->GetXaxis()->GetLabels();
	TH1F* final[5];
	vector<string> binnames;
	for(int i=0; i<5;i++) { 
		final[i]=new TH1F(Form("final_%d",i),Form("final_%d",i),maxbins,0,maxbins); 
		for(int j=1;j<=maxbins;j++) {
			 current=((TObjString*)(slist->At(j-1)))->GetString().Data();		 
			 final[i]->SetBinContent(j,hours[i][current]);
			 final[i]->GetXaxis()->SetBinLabel(j,current);
			 binnames.push_back(current);
		}
	}
	THStack* st=new THStack("CEHours","");
	for(int i=0;i<5;i++) { 
		if(i!=4) final[i]->SetFillColor(i+2); 
		st->Add(final[i]);
	}
	cout << maxbins << endl;
	st->Draw();
	for(int j=1;j<=maxbins;j++) {
		cout << binnames[j-1].c_str() << endl;
		st->GetXaxis()->SetBinLabel(j,binnames[j-1].c_str());
		st->GetXaxis()->LabelsOption("v");
	}
	TLegend* leg=new TLegend(0.8,0.8,0.89,0.89);
	leg->AddEntry(final[0],"cms","f");
	leg->AddEntry(final[1],"lhcb","f");
	leg->AddEntry(final[2],"atlas","f");
	leg->AddEntry(final[3],"others","f");
	leg->AddEntry(final[4],"Failed","f");
	st->Draw();
	leg->Draw();
}

/*
void RBPlot::hoursCEVO(char* sdate,char* edate,TCut cut) {
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	
}
*/

void RBPlot::usefullEffibyVAR(char* var,char* sdate,char* edate,TCut cut,char* filename) {
 map<string,vector<double> >  xls;
 gStyle->SetOptStat(0);
 pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
 TH1F* totaltime=NULL;
 TH1F* succtime=NULL;
 totaltime=(TH1F*)gROOT->FindObject("totalTime");
 succtime=(TH1F*)gROOT->FindObject("succTime");
 if(totaltime!=NULL) totaltime->Reset();
 if(succtime!=NULL)  succtime->Reset();
 TCut scut(Form("userinterface_regjob_Epoch > %d",interval.first));
 TCut ecut(Form("userinterface_regjob_Epoch < %d",interval.second));
 TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
 mytree->Draw(Form("%s >> totalTime",var),"(logmonitor_wn_Time/3600)"*(cut&&(scut&&ecut)),"goff");
 mytree->Draw(Form("%s >> succTime",var),"(logmonitor_wn_Time/3600)"*(cut&&suc&&(scut&&ecut)),"goff");
 gDirectory->GetObject("totalTime",totaltime);
 gDirectory->GetObject("succTime",succtime);
 int nbins=succtime->GetNbinsX();
 THashList* names=succtime->GetXaxis()->GetLabels();
 string currs;
 for(int i=0;i<nbins;i++) {
 	currs=((TObjString*)names->At(i))->GetString().Data();	
	xls[currs].push_back(succtime->GetBinContent(i+1));	
 }	
 if(totaltime!=NULL && succtime!=NULL) {
 	succtime->LabelsOption("a","X");
 	totaltime->LabelsOption("a","X");
 	succtime->Divide(totaltime);
 	succtime->SetTitle("");
//		succtime->SetXTitle("CE");
 	succtime->SetYTitle("Efficiency");
 	succtime->LabelsOption(">v","X");
	succtime->Draw();
 }
	// Dumping the CE information
	nbins=succtime->GetNbinsX();
	names=succtime->GetXaxis()->GetLabels();
	for(int i=0;i<nbins;i++) {
		currs=((TObjString*)names->At(i))->GetString().Data();
		xls[currs].push_back(succtime->GetBinContent(i+1));
	}
	map<string,vector<double> >::iterator ixls;
	if(filename!=NULL) {
		ofstream outfile(filename);
		outfile << var << "\t" << "Success Hours" << "\t" << "Efficiency" << endl;
		for(ixls=xls.begin(); ixls!=xls.end(); ixls++) 
		outfile << (*ixls).first << "\t" << (*ixls).second[0] << "\t" << (*ixls).second[1] << endl; 
		outfile.close();	
	}
}


void RBPlot::usefullEffi(char* sdate,char* edate,TCut cut,char* filename) {
	map<string,vector<double> > xls;
	gStyle->SetOptStat(0);
	pair<UInt_t,UInt_t> interval=getInterval(sdate,edate);
	TH1F* totaltime=NULL;
	TH1F* succtime=NULL;
        totaltime=(TH1F*)gROOT->FindObject("totalTime");
	succtime=(TH1F*)gROOT->FindObject("succTime");
	if(totaltime!=NULL) totaltime->Reset();
	if(succtime!=NULL)  succtime->Reset();
	cout << "stime=" << interval.first << "etime=" << interval.second << endl;
	TCut scut(Form("userinterface_regjob_Epoch > %d",interval.first));
        TCut ecut(Form("userinterface_regjob_Epoch < %d",interval.second));
//	TCut suc("type.fData==\"REGISTERED-RAN-SUCCESS\" || type.fData==\"REGISTERED-RAN-RESUBMITTED-SUCCESS\"");
	TCut suc("type.fData==\"REGISTERED-DONE-RAN\" || type.fData==\"REGISTERED-DONE-RAN-CLEARED\" || type.fData==\"REGISTERED-DONE\"");
	mytree->Draw("CE.fData >> totalTime","(logmonitor_wn_Time/3600)"*(cut&&(scut&&ecut)),"goff");
	mytree->Draw("CE.fData >> succTime","(logmonitor_wn_Time/3600)"*(cut&&suc&&(scut&&ecut)),"goff");
	gDirectory->GetObject("totalTime",totaltime);
	gDirectory->GetObject("succTime",succtime);
	int nbins=succtime->GetNbinsX();
	THashList* names=succtime->GetXaxis()->GetLabels();
	string currs;
	for(int i=0;i<nbins;i++) {
		currs=((TObjString*)names->At(i))->GetString().Data();	
		xls[currs].push_back(succtime->GetBinContent(i+1));	
	}	
	if(totaltime!=NULL && succtime!=NULL) {
		succtime->LabelsOption("a","X");
		totaltime->LabelsOption("a","X");
		succtime->Divide(totaltime);
		succtime->SetTitle("");
//		succtime->SetXTitle("CE");
		succtime->SetYTitle("Efficiency");
		succtime->LabelsOption(">v","X");
		succtime->Draw();
	}
	// Dumping the CE information
	nbins=succtime->GetNbinsX();
	names=succtime->GetXaxis()->GetLabels();
	for(int i=0;i<nbins;i++) {
		currs=((TObjString*)names->At(i))->GetString().Data();
		xls[currs].push_back(succtime->GetBinContent(i+1));
	}
	map<string,vector<double> >::iterator ixls;
	if(filename!=NULL) {
		ofstream outfile(filename);
		outfile << "CE" << "\t" << "Success Hours" << "\t" << "Efficiency" << endl;
		for(ixls=xls.begin(); ixls!=xls.end(); ixls++) 
		outfile << (*ixls).first << "\t" << (*ixls).second[0] << "\t" << (*ixls).second[1] << endl; 
		outfile.close();	
	}
} 



void RBPlot::cumulative(char* variable,char* weight,Int_t nbins, Float_t xmin, Float_t xmax,char* tx,char* ty,char* ty1,char* cuts,char* hname,Int_t r) {
	gStyle->SetOptStat(0);	
	TH1F* cum=new TH1F(hname,hname,nbins,xmin,xmax);
	TH1F* njobs=new TH1F(Form("n_%s",hname),hname,nbins,xmin,xmax);
	mytree->Draw(Form("%s >> %s",variable,hname),Form("(%s)*(%s)",weight,cuts),"goff");
	mytree->Draw(Form("%s >> n_%s",variable,hname),Form("%s",cuts),"goff");
	TH1F* cumint=(TH1F*)cum->Clone(Form("cumint_%s",hname));
 	cumint->Reset();
	TH1F* binint=(TH1F*)cum->Clone(Form("binint_%s",hname));
	for(int i=0; i<cum->GetNbinsX();i++) {
		cumint->SetBinContent(i+1,cum->Integral(1,i+1));
	}
	cumint->Scale(1./cum->Integral());
//	cumint->Draw();
	binint->Rebin(r);
	binint->Scale(1./cum->Integral());
	TCanvas* v=new TCanvas("cum","cum",600,300);
	v->Divide(2,1);
	v->cd(1);
 	binint->Draw();
	binint->SetXTitle(tx);	
 	binint->SetYTitle(ty);	
	binint->GetYaxis()->SetTitleOffset(1.3);
	v->cd(2);
	njobs->Rebin(r);
	njobs->Scale(1./njobs->Integral());
	njobs->Draw();	
	njobs->SetTitle("");
	njobs->SetXTitle(tx);
	njobs->GetYaxis()->SetTitleOffset(1.3);
	njobs->SetYTitle(ty1);
}


Int_t RBPlot::getNBins(pair<UInt_t,UInt_t> interval,Int_t time) {
	return ((interval.second-interval.first)/time);
}


pair<UInt_t,UInt_t> RBPlot::getInterval(char* sdate,char* edate) {
	TDatime stime(sdate);
	TDatime etime(edate);
	UInt_t st=stime.Convert(true);
	UInt_t et=etime.Convert(true); 
	return pair<UInt_t,UInt_t>(st,et);
} 
